import './student.less'
import React from 'react';
import { connect } from 'dva';
import { CheckCircleOutlined,CheckCircleFilled,DownloadOutlined} from '@ant-design/icons';
import { Layout, Button } from 'antd';
import BaseComponent from 'components/BaseComponent';
import Toolbar from 'components/Toolbar';
import SearchBar from 'components/SearchBar';
import DataTable, {Oper} from 'components/DataTable';
import Image from 'components/Image'
import { ModalForm, ModalTable } from 'components/Modal';
import createColumns from './columns';
import $$ from "cmn-utils";
import Icon from "components/Icon";
const { Content, Header, Footer } = Layout;
const Pagination = DataTable.Pagination;
import * as QueryString from 'query-string'
import { Modal,Row, Col } from 'antd';
import { noticeGlobal} from "@/utils/core";
import { object } from 'prop-types';
import { Popconfirm, Table,Space } from 'antd';
import moment from 'moment';

@connect(({ stuDeteail, loading }) => ({
  stuDeteail,
  loading: loading.models.stuDeteail
}))
export default class extends BaseComponent {
  state = {
    record: null,
    visible: false,
    roleFormVisible: false,
    rows: [],
    showPhoto:false,
    photoArr:[],
    showPhotoArr:[],
    quesPotoJson:{},
    moreData :{
      examPaperQuestionInfoVos:[],
      selfScore:0,
      succNum:0,
      errorNum:0,
      selfAnswer:{},
    },
    columns:[
      {
        title:'姓名',
        dataIndex:"realname",
        key:"realname",
      },
      {
        title:'课次',
        dataIndex:"lectureName",
        key:"lectureName",
      },
      {
        title:'创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        render:text => moment.utc(text).format('YYYY-MM-DD HH:mm')
      },
      {
        title:'照片',
        key: 'filePath',
        dataIndex: 'filePath',
        render:text => <span className="delePhoto">
        <Image src={text} style={{ width: 50 }} previewList={this.state.showPhotoArr}
      />
      </span>
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <Popconfirm
          title="确定要删除吗？"
          onConfirm={e => this.delePhoto(text,record.keys)}
          okText="确定"
          cancelText="取消"
        >
                    <Icon type="trash" className="delePhotoIcon" />
      </Popconfirm>
        ),
      },
    ]
  };
  componentDidMount() {
    const {location,dispatch} = this.props;
    const params =  QueryString.parse(location.search);
      const data  = this.props.stuDeteail.pageData;
      this.setState({lessonId:params.i,classId:params.c,uid: params.d});
      dispatch({
        type:'stuDeteail/getPageInfo',
        payload: {
          lessonId:params.i,uid:params.d,pageNum:data.pageNum,
          pageSize:data.pageSize,},
      });
  }

  handleDelete = records => {
    const { rows } = this.state;

    this.props.dispatch({
      type: 'users/remove',
      payload: {
        records,
        success: () => {
          this.setState({
            rows: rows.filter(
              item => !records.some(jtem => jtem.id === item.id)
            )
          });
        }
      }
    });
  };

  showRoleForm = record =>{
    if (!record) return;
    if ($$.isArray(record) && !record.length) return;
    this.setState({
      record,
      roleFormVisible: true,
    });
    this.props.dispatch({
      type: 'users/getUserRoleList',
      payload: {'userId': record.id},
    })
  };

  handleActive = (record, val) =>{
    this.props.dispatch({
      type: 'users/updateIsActive',
      payload:{
        record,
        val,
      }
    })
  };
  exportExl(){
    const data  = this.props.stuDeteail.pageData;
    const jsonData = {
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      classId:this.state.classId,
      lessonId:this.state.lessonId,
      uid:this.state.uid,
    }
    this.props.dispatch({
      type: 'stuDeteail/exportPageInfo',
      payload: {
        pageData: jsonData
      }
    })
  }
  quesPhoto(e) {
    const data = {
      lectureId: e.id,
      uid: this.state.uid
    };
    this.setState({
      showPhoto:true,
      photoArr:[],
      quesPotoJson:e,
    })
    $$.post('/api/user/photo/list',data).then(res => {
      if ( res.data.length ) {
        const arr = [];
        res.data.map((item,key) => {
          arr.push(item.filePath);
          res.data[key] = {
            ...res.data[key],
            realname:e.realname,
            lectureName:e.lectureName,
            keys:key
          }
        })
        const arr2 = res.data;
        this.setState({
          photoArr:res.data,
          showPhotoArr:arr
        })
      }
    }) 
  }
  delePhoto(item,key){
    $$.del('/api/user/photo/delete/'+item.id).then(res => {
      this.quesPhoto(this.state.quesPotoJson);
      // const photoArr = this.state.photoArr;
      // const showPhotoArr = this.state.showPhotoArr;
      // photoArr.splice(key,1)
      // showPhotoArr.splice(key,1)
      // this.setState({
      //   photoArr,
      //   showPhotoArr
      // })
      console.log(res);
    })
  }
  closeModa() {
    this.setState({
      visible: false,
      showPhoto: false,
    })
  }

 secondsFormat( s ) { 
  var day = Math.floor( s/ (24*3600) ); // Math.floor()向下取整 
  var hour = Math.floor( (s - day*24*3600) / 3600); 
  var minute = Math.floor( (s - day*24*3600 - hour*3600) /60 ); 
  var second = s - day*24*3600 - hour*3600 - minute*60;
  if (hour) {
    return  + hour + "时" + minute + "分" + second + "秒"; 
  } else if (minute) {
    return  + minute + "分" + second + "秒"; 
  } else {
    return  + second + "秒"; 
  }
}
  quesInfo(e) {
    // const data = e.id;
    const data = {
      lectureId: e.id,
      // lectureId: 33,
      userId: this.state.uid
      // userId: 19
    };
    // $$.post('/api/examActivityResult/student/getExamDetail ',data).then(res => {
    //   console.log(res)
    // }) 
    // $$.post('/api/examActivityResult/student/getExamSelfResult ',data).then(res => {
    //   console.log(res)
    // })  
    // return;
    $$.post('/api/examActivityResult/student/examDetail',data).then(res => {
      console.log(typeof  res.data.standardAnswer)
      if ( res.code && res.code === 200 ) {
          const stuData = res.data;
          const ansJson = {};
          let succNum = stuData.examPaperQuestionInfoVos.length;
          let errorNum = 0;
          if (!stuData.standardAnswer) {
            noticeGlobal.error('当前暂无试卷数据');
            return;
          }
          if (!stuData.selfAnswer) {
            noticeGlobal.error('当前暂无学生数据');
            return;
          }
          for ( const data of stuData.standardAnswer ) {
            if ( !ansJson[data.examPaperQuestionInfoId] ) {
              ansJson[data.examPaperQuestionInfoId] = {};
            }
            ansJson[data.examPaperQuestionInfoId]['answer'] = data.answer;
          }
          for ( const data of stuData.selfAnswer ) {
            ansJson[data.examPaperQuestionInfoId]['selfAnswer'] = data.answer;
            ansJson[data.examPaperQuestionInfoId]['answerStu'] = true;
          }
          for (  const data in  ansJson) {
            const ques  = ansJson[data];
            if ( ques.answer !== ques.selfAnswer ) {
              succNum-=1;
              errorNum+=1;
              ques.answerStu = false;
            }
          }
          const moreData = {
            examPaperQuestionInfoVos:stuData.examPaperQuestionInfoVos,
            selfScore:stuData.selfScore,
            succNum,
            errorNum,
            selfAnswer:ansJson,
          }
          this.setState({
            visible: !this.state.visible,
            moreData
          })
      } else {
        noticeGlobal.error('找不到试卷');
      }
    })
  }
  render() {
    const { stuDeteail, loading, dispatch } = this.props;
    const { pageData, roleList, userRoleIds } = stuDeteail;
    const columns = createColumns(this);
    const { rows, record, visible, roleFormVisible } = this.state;

    const searchBarProps = {
      columns,
      onSearch: values => {
        dispatch({
          type: 'stuDeteail/getPageInfo',
          payload: {
            pageData: pageData.filter(values).jumpPage(1, 10)
          }
        });
      }
    };

    const dataTableProps = {
      loading,
      columns,
      // rowKey: 'id',
      dataItems: pageData,
      // selectType: 'checkbox',
      // showNum: true,
      isScroll: true,
      // selectedRowKeys: rows.map(item => item.id),
      onChange: ({ pageNum, pageSize }) => {
        const {location,dispatch} = this.props;
        const params =  QueryString.parse(location.search);
        const data  = this.props.stuDeteail.pageData;
        const jsonData = {
            lessonId:params.i,uid:params.d,pageNum:data.pageNum,
            pageSize:data.pageSize,
        }
        dispatch({
          type: 'stuDeteail/getPageInfo',
          payload: jsonData
        });
      },
      onSelect: (keys, rows) => this.setState({ rows })
    };

    const roleListFormProps = {
      loading,
      record,
      visible: roleFormVisible,
      title: '编辑角色',
      // columns: roleColumns ,
      columns:  [
        {
          title: '角色名',
          name: 'roleName',
          tableItem: {},
        }],
      modalOpts:{
        width: 700
      },
      tableProps: {dataSource : roleList, pagination: false, value: userRoleIds,},

      onCancel: ()=>{
        this.setState({
          record: null,
          roleFormVisible: false,
        })
      },
      onSubmit: (values, rows)=>{
        this.props.dispatch({
          type: 'users/updateUserRole',
          payload: {
            record,
            roleIds: rows.map(item => item.id),
            success: ()=>{
              this.setState({
                record: null,
                roleFormVisible: false,
              });
            }
          }
        });
      },
    };

    const modalFormProps = {
      loading,
      record,
      visible,
      columns,
      modalOpts: {
        width: 700
      },
      onCancel: () => {
        this.setState({
          record: null,
          visible: false
        });
      },
      onSubmit: values => {
        let type = 'users/save';
        if (values.id) type = 'users/update';
        dispatch({
          type,
          payload: {
            values,
            success: () => {
              this.setState({
                record: null,
                visible: false
              });
            }
          }
        });
      }
    };

    return (
      <Layout className="full-layout">
        <Header>
          <Toolbar
            appendLeft = {
              <Button type="default" icon={<DownloadOutlined />} onClick={this.exportExl.bind(this)}>
              导出
            </Button>
            }
            // appendLeft={
            //   <Button.Group>
            //     <Button type="primary" icon={<PlusOutlined />} onClick={this.onAdd}>
            //       新增
            //     </Button>
            //     <Button
            //       disabled={!rows.length}
            //       onClick={e => this.onDelete(rows)}
            //       icon={<DeleteOutlined />}
            //     >
            //       删除
            //     </Button>
            //   </Button.Group>
            // }
            // pullDown={<SearchBar group="abc" {...searchBarProps} />}
          >
            <SearchBar group="abc" {...searchBarProps} />
          </Toolbar>
        </Header>
        <Content>
          <DataTable {...dataTableProps} />
        </Content>
        <Footer>
          <Pagination {...dataTableProps} />
        </Footer>
        <Modal
           title="课程照片"
           visible={this.state.showPhoto}
           onCancel={this.closeModa.bind(this)}
           footer={null}
           width={1000}
        >
          <Table dataSource={this.state.photoArr} columns={this.state.columns} />
        </Modal>
        <Modal
          title="答题详情"
          visible={this.state.visible}
          onCancel={this.closeModa.bind(this)}
          footer={null}
          width={1000}
        >
         <Row>
          <Col span={8}>本次成绩：{this.state.moreData.selfScore}分</Col>
          <Col span={8} className="green">正确：{this.state.moreData.succNum}题</Col>
          <Col span={8} className="red">错误：{this.state.moreData.errorNum}题</Col>
        </Row>
        {
          this.state.moreData.examPaperQuestionInfoVos.map((item,key) => {
            return <Row className="marginTop" key={key}>
                  <Col span={20}>
                    {
                      this.state.moreData.selfAnswer[item.id].answerStu &&
                      <Icon type="check" className="green"/>
                    }
                    {
                      !this.state.moreData.selfAnswer[item.id].answerStu &&
                      <Icon type="close" className="red"/>
                    }
                    {item.name}
                  </Col>
                  {
                      !this.state.moreData.selfAnswer[item.id].answerStu &&
                    <Col span={4} className="red">正确答案：{this.state.moreData.selfAnswer[item.id].answer}</Col>
                  }
                  {
                    item.type === 2 &&
                    <Col span={6} className={['marginTop',this.state.moreData.selfAnswer[item.id].selfAnswer === '正确' ? 'blue' : null]}>
                            {
                              this.state.moreData.selfAnswer[item.id].selfAnswer !== '正确' &&
                              <CheckCircleOutlined twoToneColor="#eb2f96" />
                           }
                           {
                              this.state.moreData.selfAnswer[item.id].selfAnswer === '正确' &&
                              <CheckCircleFilled twoToneColor="#eb2f96" />
                           }
                      &nbsp;
                    正确</Col>
                  }
                  {
                    item.type === 2 &&
                    <Col span={6} className={['marginTop',this.state.moreData.selfAnswer[item.id].selfAnswer === '错误' ? 'blue' : null]}>
                       {
                              this.state.moreData.selfAnswer[item.id].selfAnswer !== '错误' &&
                              <CheckCircleOutlined twoToneColor="#eb2f96" />
                           }
                           {
                              this.state.moreData.selfAnswer[item.id].selfAnswer === '错误' &&
                              <CheckCircleFilled twoToneColor="#eb2f96" />
                           }
                    错误</Col>
                  }
                  {
                    item.type === 1 && item.optionInfos.map((items,keys) => {
                         return <Col key={keys} span={12} className={['marginTop',this.state.moreData.selfAnswer[item.id].selfAnswer === items.optionOrder ? 'blue' : null]}>
                           {
                              this.state.moreData.selfAnswer[item.id].selfAnswer !== items.optionOrder &&
                              <CheckCircleOutlined twoToneColor="#eb2f96" />
                           }
                           {
                              this.state.moreData.selfAnswer[item.id].selfAnswer === items.optionOrder &&
                              <CheckCircleFilled twoToneColor="#eb2f96" />
                           }
                           &nbsp;
                           <span className="options">
                           {items.optionOrder}.&nbsp;{items.name}

                           </span>
                           </Col>
                    })
                  }
                  {/* <Col span={6} className="marginTop"><CheckCircleOutlined twoToneColor="#eb2f96" />
                  11212</Col> */}
                </Row>
          })
        }
        </Modal>
      </Layout>
    );
  }
}
